package com.tanhua.management.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.MessagesApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Messages;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.management.vo.MessagesDetailsVo;
import com.tanhua.management.vo.MessagesVo;
import com.tanhua.management.vo.PageResult;
import com.tanhua.management.vo.Totals;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author 王加鑫
 * @Date 2021/09/16 21:27
 * @Since JDK 1.8
 */
@Service
public class MessagesService {

    @Reference(version = "1.0.0")
    private MessagesApi messagesApi;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 查看消息详情
     * @return
     */
    public MessagesDetailsVo queryMessagesDetails(String id) {
        //根据动态id查询消息表
        Messages messages = this.messagesApi.queryMessages(id);
        if (ObjectUtil.isEmpty(messages)) {
            return null;
        }
        //根据动态id查询动态表
        Publish publish = this.quanZiApi.queryPublishById(messages.getMId().toHexString());

        //根据用户id查询UserInfo用户详情表
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(messages.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        MessagesDetailsVo messagesDetailsVo = new MessagesDetailsVo();
        messagesDetailsVo.setId(messages.getId().toHexString());
        //发布动态的用户id
        messagesDetailsVo.setUserId(userInfo.getUserId());
        //用户头像
        messagesDetailsVo.setUserLogo(userInfo.getLogo());
        //用户动态图片
        messagesDetailsVo.setMedias(publish.getMedias().toArray(new String[publish.getMedias().size()]));
        messagesDetailsVo.setCommentCount(messages.getCommentCount());
        messagesDetailsVo.setCreateDate(messages.getCreateDate());
        //用户昵称
        messagesDetailsVo.setNickname(userInfo.getNickName());
        messagesDetailsVo.setForwardingCount(messages.getForwardingCount());
        //动态点赞数
        Long likeCount = this.quanZiApi.queryLikeCount(messages.getMId().toHexString());
        messagesDetailsVo.setLikeCount(Convert.toInt(likeCount));
        //动态评论数
        Integer commentCount = this.quanZiApi.queryCommentCount(messages.getMId().toHexString());
        messagesDetailsVo.setCommentCount(commentCount);
        //动态的文本内容
        messagesDetailsVo.setText(publish.getText());
        messagesDetailsVo.setState(Convert.toInt(messages.getState()));
        messagesDetailsVo.setTopState(messages.getTopState());
        return messagesDetailsVo;
    }

    /**
     * 查询消息列表
     * userId不为空则查询单个用户
     * userId为空查询所有
     * @param pageSize
     * @param page
     * @param sortProp 排序字段
     * @param sortOrder 排序方式
     * @param mid 消息Id
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param userId 用户id
     * @param state 审核状态
     * @return
     */
    public PageResult queryMessagesList(Integer pageSize, Integer page, String sortProp, String sortOrder, String mid, String startTime, String endTime, Long userId, String state) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //根据条件查询MessagesList数据

        List<MessagesVo> messagesVoList = new ArrayList<>();
        //如果用户id不为空
        if(userId != null){
            PageInfo<Messages> pageInfo = this.messagesApi.queryMessagesList(pageSize,page,sortProp,sortOrder,mid,startTime,endTime,userId);
            pageResult.setCounts(pageInfo.getTotal());
            pageResult.setPages(pageInfo.getTotal() % pageSize == 0 ? (pageInfo.getTotal() / pageSize) : (pageInfo.getTotal() / pageSize + 1));
            List<Messages> messagesList = pageInfo.getRecords();
            if(CollUtil.isEmpty(messagesList)){
                return pageResult;
            }
            //获取到所有的publishId的集合
            List<String> publishIds = new ArrayList<>();
            for (Messages messages : messagesList) {
                publishIds.add(messages.getMId().toHexString());
            }

            List<Publish> publishList = this.quanZiApi.queryPublishList(publishIds, page, pageSize);
            //这个用户所发布的所有动态
//            List<Publish> publishList = this.quanZiApi.queryPublishList(userId, page, pageSize,sortOrder);
            if(CollUtil.isEmpty(publishList)){
                return pageResult;
            }
            //这个用户的详细信息
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
            for (Messages messages : messagesList) {
                for (Publish publish : publishList) {
                    if(messages.getMId().toHexString().equals(publish.getId().toHexString())){
                        messagesVoList = this.returnMessagesVo(messages, publish, userInfo, messagesVoList);
                    }
                }
            }

            if(CollUtil.isEmpty(messagesVoList)){
                return pageResult;
            }
            pageResult.setItems(messagesVoList);
            return pageResult;
        }

        pageResult = queryMessagesAll(pageSize, page, sortProp, sortOrder, mid, startTime, endTime, userId, state, pageResult, messagesVoList);
        pageResult.setTotals(returnTotals());

        return pageResult;
    }


    /*public PageResult queryMessagesList(Integer pageSize, Integer page, String sortProp, String sortOrder, String mid, String startTime, String endTime, Long userId, String state) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //根据条件查询MessagesList数据

        List<MessagesVo> messagesVoList = new ArrayList<>();
        //如果用户id不为空
        if(userId != null){
            PageInfo<Messages> pageInfo = this.messagesApi.queryMessagesList(pageSize,page,sortProp,sortOrder,mid,startTime,endTime,userId);
            List<Messages> messagesList = pageInfo.getRecords();
            if(CollUtil.isEmpty(messagesList)){
                return pageResult;
            }
            //这个用户所发布的所有动态
            List<Publish> publishList = this.quanZiApi.queryPublishList(userId, page, pageSize,sortOrder);
            if(CollUtil.isEmpty(publishList)){
                return pageResult;
            }
            //这个用户的详细信息
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
            for (Publish publish : publishList) {
                for (Messages messages : messagesList) {
                    if(messages.getMId().toHexString().equals(publish.getId().toHexString())){
                        messagesVoList = this.returnMessagesVo(messages, publish, userInfo, messagesVoList);
                    }
                }
            }
            if(CollUtil.isEmpty(messagesVoList)){
                return pageResult;
            }


            //分页
            Integer page1 = Math.max(1, page == null ? 1 : page);
            Integer pageSize1 = Math.max(1, pageSize == null ? 1 : pageSize);
            List<MessagesVo> newMovements = new ArrayList<>();
            int startIndex = (page1 - 1) * pageSize1;
            if (startIndex < messagesVoList.size()) {
                int endIndex = startIndex + pageSize1 - 1;
                if (endIndex >= messagesVoList.size()) {
                    endIndex = messagesVoList.size() - 1;
                }

                newMovements = messagesVoList.subList(startIndex, endIndex + 1);
            }

            pageResult.setCounts(messagesVoList.size());
            pageResult.setPages((int) Math.ceil(messagesVoList.size() / pageSize));
            pageResult.setItems(newMovements);

            return pageResult;
        }

        pageResult = queryMessagesAll(pageSize, page, sortProp, sortOrder, mid, startTime, endTime, userId, state, pageResult, messagesVoList);
        pageResult.setTotals(returnTotals());

        return pageResult;
    }*/

    /**
     * 用户id为空查所有
     * @param pageSize
     * @param page
     * @param sortProp
     * @param sortOrder
     * @param mid
     * @param startTime
     * @param endTime
     * @param userId
     * @param state
     * @return
     */
    private PageResult queryMessagesAll(Integer pageSize, Integer page, String sortProp, String sortOrder, String mid,
                                        String startTime, String endTime, Long userId, String state,PageResult pageResult,List<MessagesVo> messagesVoList){
        //用户id为空查所有
        PageInfo<Messages> pageInfo = this.messagesApi.queryMessagesList(pageSize,page,sortProp,sortOrder,mid,startTime,endTime,userId,state);
        pageResult.setCounts(pageInfo.getTotal());
        pageResult.setPages(pageInfo.getTotal() % pageSize == 0 ? (pageInfo.getTotal() / pageSize) : (pageInfo.getTotal() / pageSize + 1));
        List<Messages> messagesList = pageInfo.getRecords();
        if(CollUtil.isEmpty(messagesList)){
            return pageResult;
        }

        List<String> publishIds = new ArrayList<>();

        //查询所有的mId(Publish表id的集合)
        for (Messages messages : messagesList) {
            publishIds.add(messages.getMId().toHexString());
        }

        List<Publish> publishList = this.quanZiApi.queryPublishList(publishIds,page,pageSize,sortOrder);
        if(CollUtil.isEmpty(publishList)){
            return pageResult;
        }

        for (Messages messages : messagesList) {
            Long myUserId = messages.getUserId();
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(myUserId);
            for (Publish publish : publishList) {
                messagesVoList = this.returnMessagesVo(messages, publish, userInfo, messagesVoList);
            }
        }
        if(CollUtil.isEmpty(messagesVoList)){
            return pageResult;
        }

        pageResult.setItems(messagesVoList);
        return pageResult;
    }

    /**
     * 状态合计
     * @param
     * @return
     */
    public List<Totals> returnTotals(){
        List<Totals> totals = new ArrayList<>();
        String[] states = {"all","3","4","5"};
        for (int i = 0; i < states.length; i++) {
            if("all".equals(states[i])){
                totals.add(new Totals("全部","all",this.messagesApi.queryMessagesCount(states[i])));
            }else if("3".equals(states[i])){
                totals.add(new Totals("待审核","3",this.messagesApi.queryMessagesCount(states[i])));
            }else if("4".equals(states[i])){
                totals.add(new Totals("已驳回","4",this.messagesApi.queryMessagesCount(states[i])));
            }else if("5".equals(states[i])){
                totals.add(new Totals("已通过","5",this.messagesApi.queryMessagesCount(states[i])));
            }
        }
        return totals;
    }






    /**
     * 整合数据
     * @param messages
     * @param publish
     * @param userInfo
     * @param messagesVoList
     * @return
     */
    public List<MessagesVo> returnMessagesVo(Messages messages,Publish publish,UserInfo userInfo,List<MessagesVo> messagesVoList){
        if(messages.getMId().toHexString().equals(publish.getId().toHexString())){
            MessagesVo messagesVo = new MessagesVo();
            messagesVo.setId(messages.getId().toHexString());
            messagesVo.setState(messages.getState()); //审核状态
            messagesVo.setText(publish.getText()); //动态文本
            messagesVo.setMedias(publish.getMedias().toArray(new String[publish.getMedias().size()])); //图片路径
            messagesVo.setUserLogo(userInfo.getLogo());
            messagesVo.setUserId(publish.getUserId()); //用户id
            messagesVo.setTopState(messages.getTopState()); //置顶状态
            messagesVo.setCommentCount(this.quanZiApi.queryCommentCount(messages.getMId().toHexString())); //评论数
            messagesVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(messages.getMId().toHexString()))); //点赞数
            messagesVo.setForwardingCount(RandomUtil.randomInt(10000)); //转发数
            messagesVo.setNickname(userInfo.getNickName());
            messagesVo.setCreateDate(messages.getCreateDate());
            messagesVo.setReportCount(0); //举报数
            messagesVoList.add(messagesVo);
        }
        return messagesVoList;
    }

    /**
     * 消息通过
     *
     * @param ids
     * @return
     */
    public String messagesPast(String[] ids) {
        String state = this.messagesApi.messagesPast(ids);
        if(ObjectUtil.isEmpty(state)){
            return null;
        }
        return state;
    }

    /**
     * 消息拒绝
     * @param ids
     * @return
     */
    public String messagesReject(String[] ids) {
        String state = this.messagesApi.messagesReject(ids);
        if(ObjectUtil.isEmpty(state)){
            return null;
        }
        return state;
    }

    /**
     * 消息撤销
     * @param ids
     * @return
     */
    public String messagesRevocation(String[] ids) {
        String state = this.messagesApi.messagesRevocation(ids);
        if(ObjectUtil.isEmpty(state)){
            return null;
        }
        return state;
    }

    /**
     * 消息置顶
     * @param id
     * @return
     */
    public String messagesTop(String id) {
        String topState = this.messagesApi.messagesTop(id);
        if(ObjectUtil.isNotEmpty(topState)){
            return topState;
        }
        return null;
    }

    /**
     * 消息取消置顶
     * @param id
     * @return
     */
    public String messagesUnTop(String id) {
        String topState = this.messagesApi.messagesUnTop(id);
        if(ObjectUtil.isNotEmpty(topState)){
            return topState;
        }
        return null;
    }
}
